package com.summer.framework.core.tenant.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.summer.framework.base.exception.SummerRuntimeException;
import com.summer.framework.core.tenant.TenantProperties;
import com.summer.framework.core.tenant.context.TenantContext;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
 * Description: 添加租户处理器
 * @auther Ice Yang
 * Date 2025/7/2 17:30
 */
@Component
@ConditionalOnProperty(name = "summer.tenant.enable", havingValue = "true",
        matchIfMissing = false // 配置不存在时，默认不创建
)
public class SummerTenantLineHandler implements TenantLineHandler {

    @Autowired
    private TenantProperties properties;

    @Override
    public String getTenantIdColumn() {
        return properties.getTenantId();
    }

    @Override
    public Expression getTenantId() {
        String tenantId = TenantContext.getTenantId();
        if(tenantId == null || tenantId.isEmpty()){
            throw new SummerRuntimeException("租户信息为空");
        }
        return new StringValue(tenantId);
    }

    @Override
    public boolean ignoreTable(String tableName) {
        // 如果设置了忽略租户
        return TenantContext.getTenantFlag();
    }
}
